package com.smart.tool.log;

import java.util.StringTokenizer;

import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * @Author gao.gwq
 * @Version LoggerFormatter.java, v 0.1 2023年11月28日 20:30 gao.gwq
 * @Description: TODO
 */
public interface LoggerFormatter {
    /**
     *
     * @param domainType 域对象
     * @param business 业务名称
     * @param bizId 业务id
     * @param msgFormate  消息 可以带站位符，可以不带占位符
     * @param paramValues 参数值，如果带占位符，会把对应值信息填充， value
     * @param paramJson 参数值 key -value 对象
     * @param resultData 返回结果
     * @return
     */
    String format(String domainType,String business,String bizId , String msgFormate, String[] paramValues,String paramJson, String resultData);

    default String printStackInfo(Throwable t) {
        if (t != null) {
            Throwable rootCause = ExceptionUtils.getRootCause(t);
            return rootCause != null ? this.getStackTrace(rootCause) : this.getStackTrace(t);
        } else {
            return null;
        }
    }

    default String getStackTrace(Throwable t) {
        return this.getStackTrace(t, this.getStackTraceDepth());
    }

    default int getStackTraceDepth() {
        return 999;
    }

    default String getStackTrace(Throwable t, int lines) {
        StringBuilder stack = new StringBuilder();
        if (t != null) {
            String linebreak = SystemUtils.LINE_SEPARATOR;
            StringTokenizer frames = new StringTokenizer(ExceptionUtils.getStackTrace(t), linebreak);
            int i = 0;

            while(frames.hasMoreTokens()) {
                ++i;
                if (i > lines) {
                    break;
                }

                stack.append(frames.nextToken()).append(this.getStackLineBreak());
            }
        }

        return stack.toString();
    }

    default String getStackLineBreak() {
        return SystemUtils.LINE_SEPARATOR;
    }
}
